'use strict';

const db = uniCloud.database();
const _ = db.command;
const collection = db.collection('wallpapers');

exports.main = async (event, context) => {
  try {
    // 验证管理员权限
    const { OPENID } = context;
    const adminInfo = await db.collection('admin_users')
      .where({
        openid: OPENID,
        status: 1
      })
      .get();
    
    // if (adminInfo.data.length === 0) {
    //   return {
    //     code: 401,
    //     message: '无管理员权限'
    //   };
    // }
    
    // 获取参数
    const { id, status } = event;
    
    // 参数验证
    if (!id) {
      return {
        code: 400,
        message: '壁纸ID不能为空'
      };
    }
    
    if (status === undefined || status === null) {
      return {
        code: 400,
        message: '状态值不能为空'
      };
    }
    
    // 验证状态值是否有效
    const validStatuses = [0, 1, 'active', 'inactive', 'approved', 'disabled'];
    if (!validStatuses.includes(status)) {
      return {
        code: 400,
        message: '无效的状态值'
      };
    }
    
    // 转换状态值为数字格式
    const normalizedStatus = status === 'active' || status === 'approved' ? 1 : 
                           status === 'inactive' || status === 'disabled' ? 0 : 
                           Number(status);
    
    // 检查壁纸是否存在
    const wallpaperInfo = await collection.doc(id).get();
    console.log('壁纸查询结果:', JSON.stringify(wallpaperInfo)); // 添加日志以便调试
    
    // 在uniCloud中，根据文档不存在时的不同返回格式进行检查
    if (!wallpaperInfo.data || (Array.isArray(wallpaperInfo.data) && wallpaperInfo.data.length === 0)) {
      return {
        code: 404,
        message: '壁纸不存在'
      };
    }
    
    // 确保originalWallpaper获取的是正确的文档对象
    const originalWallpaper = Array.isArray(wallpaperInfo.data) ? wallpaperInfo.data[0] : wallpaperInfo.data;
    
    // 开始事务
    const transaction = await db.startTransaction();
	console.log('开始事务', transaction);
    try {
      // 更新壁纸状态
      await transaction.collection('wallpapers')
        .doc(id)
        .update({
          status: normalizedStatus,
          updateTime: new Date()
        });
      
      // 记录操作日志
      await transaction.collection('admin_logs').add({
        adminId: adminInfo.data[0]?._id || 'unknown',
        adminName: adminInfo.data[0]?.username || 'unknown',
        action: normalizedStatus === 1 ? 'activateWallpaper' : 'deactivateWallpaper',
        wallpaperId: id,
        wallpaperTitle: originalWallpaper.title || '',
        beforeStatus: originalWallpaper.status || 0,
        afterStatus: normalizedStatus,
        params: { id, status },
        success: true,
        createTime: new Date()
      });
      
      // 提交事务
      await transaction.commit();
      
      // 更新成功，返回新状态
      return {
        code: 0,
        message: normalizedStatus === 1 ? '壁纸上架成功' : '壁纸下架成功',
        data: {
          id,
          status: normalizedStatus === 1 ? 'approved' : 'disabled',
          updateTime: new Date()
        }
      };
    } catch (transError) {
      // 回滚事务
      await transaction.rollback();
      console.error('更新壁纸状态事务失败:', transError);
      
      // 记录错误日志
      try {
        await db.collection('admin_logs').add({
          adminId: adminInfo.data[0]?._id || 'unknown',
          adminName: adminInfo.data[0]?.username || 'unknown',
          action: normalizedStatus === 1 ? 'activateWallpaper' : 'deactivateWallpaper',
          wallpaperId: id,
          params: { id, status },
          success: false,
          error: transError.message,
          createTime: new Date()
        });
      } catch (logError) {
        console.error('记录错误日志失败:', logError);
      }
      
      return {
        code: 500,
        message: '更新壁纸状态失败，请稍后重试',
        error: transError.message
      };
    }
  } catch (error) {
    console.error('更新壁纸状态主错误:', error);
    
    // 记录错误日志
    try {
      await db.collection('admin_logs').add({
        action: 'updateWallpaperStatus',
        params: event,
        success: false,
        error: error.message,
        createTime: new Date()
      });
    } catch (logError) {
      console.error('记录错误日志失败:', logError);
    }
    
    return {
      code: 500,
      message: '服务器内部错误，请稍后重试',
      error: error.message
    };
  }
};